<?php
/**
 *
 * Author:苏光盼
 * Date:2020/6/21 下午11:00
 * Class:Pri.php
 * Web:https://app.admin.suanzisu.com
 * Project:通用APP后台管理系统
 *
 */

namespace App\Logic;


use App\Model\GroupPriMap;
use App\Model\Privileges as PriModel;
use App\Util\Common;
use EasySwoole\Http\Request;
use EasySwoole\ORM\Exception\Exception;

class Pri
{
    /**
     * @param int $group_id
     * @param bool $has
     * @param array $limit [1,10]
     *
     * @param string|null $key
     *
     * @return array
     * @throws Exception
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \Throwable
     */
    public static function getGroupPri( int $group_id, $has , array $limit, string $key = null) :array
    {
        if( $has  ){
            $where  = "`map`.`group_id` = $group_id";
            if( $key  ){
                $where .= " AND ( `pr`.`url` like '%$key%' OR `pr`.`desc` like '%$key%' OR `m`.`title` like '%$key%' ) ";
            }
            return self::getPrisWithGroup($where,$limit);
        } else {
            return self::getPrisWithoutGroup($group_id, $limit, $key);
        }


    }

    /**
     * @param Request $req
     *
     * @return array
     * 列出所有的后台权限，如果有条件则根本条件获取
     * @throws Exception
     * @throws \Throwable
     */
    public static function pris(Request $req)
    {
        $limit = Common::limit($req);
        $key = $req->getQueryParam('key');
        $role_menu_id = (int) $req->getQueryParam('role_menu_id');
        $wh = [];
        if( $key ){
            $wh =   ['pr.desc' => ['%'.$key.'%','like'],'pr.url'=> ['%'.$key.'%','like','OR']];;
        }
        if( $role_menu_id > 0 ) {
            $wh += ['pr.role_menu_id'=> $role_menu_id];
        }
        return self::getPris($wh,$limit);
    }

    /**
     * @param Request $req
     *
     * @return bool
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws Exception
     * @throws \Throwable
     * 保存新增或修改后的权限
     */
    public static function save( Request $req) : bool
    {
        $data = $req->getParsedBody('data');
        $mode = PriModel::create();
        if( isset($data['url']) && $data['url']) $data['url'] = trim($data['url'],'/');
        if( isset($data['id']) && $data['id'] > 0){
            $ret = (int)$mode->update($data);
        } else {
            unset($data['id']);
            $ret = (int)$mode->data($data)->save();
        }
        return $ret > 0;
    }


    /**
     * @param int $group_id
     *
     * @return array|null
     * @throws Exception
     * @throws \Throwable
     * 根据group_id获取后台用户权限urls
     */
    public static function getPrisUrlByGroupId( int $group_id) : ? array
    {
        $role = GroupPriMap::create()->alias('g')->where('g.group_id',$group_id)
            ->field('p.url')
            ->join('privileges p','g.pri_id = p.id')
            ->all();
        return array_column($role,'url');
    }


    /**
     * @param array $where
     * @param array $limit
     *
     * @return array
     * @throws Exception
     * @throws \Throwable
     * 获取所有权限 with role_menu
     */
    private static function getPris( array $where,array $limit) {
        $mode = PriModel::create()->alias('pr')->limit(...$limit);
        if( $where ){
            $mode->where($where);
        }
        $mode->order('pr.id','desc')
            ->field('pr.id,pr.desc,pr.url,m.title,pr.role_menu_id')
            ->join('role_menu m','m.id = pr.role_menu_id','LEFT')
            ->withTotalCount();
        $data = $mode->all();
        $rows = $mode->lastQueryResult()->getTotalCount();
        return ['data' => $data, 'rows' =>$rows];
    }

    /**
     * @param $where
     * @param array $limit
     *
     * @return array
     * @throws Exception
     * @throws \Throwable
     * 获取某个组所拥有的权限
     */
    private static function getPrisWithGroup($where , array $limit)
    {
        $mode = GroupPriMap::create()->alias('map')->limit(...$limit);
        if( $where )
        {
            $mode->where($where);
        }
        $mode->order('map.id','desc')
            ->field('pr.id,pr.desc,pr.url,m.title,pr.role_menu_id,map.id as map_id')
            ->join('privileges pr','map.pri_id = pr.id','LEFT')
            ->join('role_menu m','m.id = pr.role_menu_id','INNER')
            ->withTotalCount();
        $data = $mode->all();
        $rows = $mode->lastQueryResult()->getTotalCount();
        return ['data' => $data,'rows' =>$rows];
    }

    /**
     * @param int $group_id
     * @param array $limit
     * @param string $key
     *
     * @return array
     * @throws Exception
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \Throwable 获取某个用户组不拥有的权限
     */
    private static function getPrisWithoutGroup( int $group_id,array $limit,string $key = null)
    {
        $mode = GroupPriMap::create()->where('group_id',$group_id);
        $pri_ids = $mode->column('pri_id');
        $priMode = PriModel::create()->limit(...$limit)->alias('pri');
        if( $pri_ids ){
            $priMode->where('pri.id',$pri_ids,'NOT IN');
        }
        if( $key )
        {
            $priMode->where(['pri.url'=> ['%'.$key.'%','like'], 'pri.desc' => ['%'.$key.'%','like','OR'],'r.title' => ['%'.$key.'%','like','OR']]);
        }
        $priMode->join('role_menu r','pri.role_menu_id = r.id','left');
        $priMode->field(['pri.id','pri.url','pri.desc','r.title']);
        $data = $priMode->withTotalCount()->order('id')->all();
        $rows = $priMode->lastQueryResult()->getTotalCount();
        return ['data' => $data,'rows'=>$rows];
    }
}